<template>
	<div class="company-add-container">
		<van-nav-bar title="新增企业" left-text="返回" left-arrow @click-left="$router.back()" />

		<van-cell-group>
			<!-- 企业名称 -->
			<van-field v-model="form.pollutionSourceName" label="企业名称" placeholder="请输入企业名称" required clearable />

			<!-- 统一社会信用代码 -->
			<van-field v-model="form.creditCode" label="统一社会信用代码" placeholder="请输入统一社会信用代码" required clearable />

		<!-- 行政区划 -->
		<FormPopupSelect
			required
			label="行政区划"
			field-key="areaCode"
			v-model:value="form.areaCode"
			dic-key="AREA_CODE"
			field="text"
			@popup-confirm="onAreaCodeSelected"
		/>

			<!-- 企业地址 -->
			<van-field v-model="form.address" label="企业地址" placeholder="请输入企业地址" required clearable />

			<!-- 法人代表 -->
			<van-field v-model="form.legalPerson" label="法人代表" placeholder="请输入法人代表姓名" required clearable />

			<!-- 法人联系电话 -->
			<van-field v-model="form.legalPersonPhone" label="法人联系电话" placeholder="请输入法人联系电话" required clearable :maxlength="20" />

			<!-- 环保负责人 -->
			<van-field v-model="form.linkman" label="环保负责人" placeholder="请输入环保负责人姓名" required clearable />

			<!-- 环保负责人联系电话 -->
			<van-field v-model="form.linkmanPhone" label="环保负责人联系电话" placeholder="请输入环保负责人联系电话" required clearable :maxlength="20" />
		</van-cell-group>

		<!-- 保存按钮 -->
		<div class="submit-section">
			<van-button type="primary" block :loading="submitting" @click="handleSave"> 保 存 </van-button>
		</div>
	</div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { post } from '@/api/request'
import { generateId } from '../constants'
import FormPopupSelect from '@/components/form-popup-select'

export default {
	name: 'CompanyAdd',
	components: {
		FormPopupSelect,
	},
	setup() {
		const router = useRouter()
		const submitting = ref(false)

		// 表单数据
		const form = reactive({
			pollutionSourceName: '',
			creditCode: '',
			areaCode: '',
			areaName: '',
			address: '',
			legalPerson: '',
			legalPersonPhone: '',
			linkman: '',
			linkmanPhone: '',
		})

		// 电话号码验证
		const validatePhone = (phone) => {
			return /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/.test(phone)
		}

		// 表单验证
		const validateForm = () => {
			if (!form.pollutionSourceName.trim()) {
				showToast('请输入企业名称')
				return false
			}

			if (!form.creditCode.trim()) {
				showToast('请输入统一社会信用代码')
				return false
			}

			if (!form.areaCode) {
				showToast('请选择行政区划')
				return false
			}

			if (!form.address.trim()) {
				showToast('请输入企业地址')
				return false
			}

			if (!form.legalPerson.trim()) {
				showToast('请输入法人代表')
				return false
			}

			if (!form.legalPersonPhone.trim()) {
				showToast('请输入法人联系电话')
				return false
			}

			if (form.legalPersonPhone && !validatePhone(form.legalPersonPhone)) {
				showToast('法人联系电话不合法')
				return false
			}

			if (!form.linkman.trim()) {
				showToast('请输入环保负责人')
				return false
			}

			if (!form.linkmanPhone.trim()) {
				showToast('请输入环保负责人联系电话')
				return false
			}

			if (form.linkmanPhone && !validatePhone(form.linkmanPhone)) {
				showToast('环保负责人联系电话不合法')
				return false
			}

			return true
		}

	// 行政区划选择
	const onAreaCodeSelected = (data) => {
		console.log('选择的行政区划:', data)
		form.areaName = data.text
		// form.areaCode 会通过 v-model 自动更新
	}

		// 保存企业信息
		const handleSave = async () => {
			if (!validateForm()) {
				return
			}

			try {
				submitting.value = true

				// 生成ID
				const submitData = {
					...form,
					id: generateId(),
				}

				const res = await post('/api/bizPollutionSourceInfo/add', submitData)

				if (res.code === '0') {
					showToast({
						type: 'success',
						message: '新增成功',
					})

					// 延迟跳转到绑定页面
					setTimeout(() => {
						router.push({
							path: '/company/bound',
							query: {
								businessId: submitData.id,
								pollutionSourceName: form.pollutionSourceName,
							},
						})
					}, 1500)
				} else {
					showToast({
						type: 'fail',
						message: res.msg || '保存失败',
					})
				}
			} catch (error) {
				console.error('保存企业信息失败:', error)
				showToast({
					type: 'fail',
					message: '保存失败，请重试',
				})
			} finally {
				submitting.value = false
			}
		}

		return {
			form,
			submitting,
			handleSave,
			onAreaCodeSelected,
		}
	},
}
</script>

<style lang="less" scoped>
.company-add-container {
	min-height: 100vh;
	background-color: #f7f8fa;

	.submit-section {
		margin: 16px;
	}
}

:deep(.van-cell-group) {
	margin: 0;
}

:deep(.van-field__label) {
	width: 120px;
}
</style>